#pragma once
#include <cstring>
#include <memory>
#include <vector>
#include <functional>
#include <mutex>
#include <nlohmann/json.hpp>
#include <framework/request.h>
#include <framework/response.h>
#include <framework/service_interface.h>
#include <shared_mutex>
namespace cpp_backend
{
    namespace framework
    {
        /**
         * @brief 事件处理器类型
         */
        using EventHandler = std::function<void(const nlohmann::json &)>;
        /**
         * @brief 服务总线（单例模式 + 观察者模式）
         * 提供服务间通信能力：
         * 1. 事件发布/订阅： 服务间异步通信
         * 2. RPC调用： 服务间同步调用
         * 3. 服务注册/发现： 管理运行中的服务实例
         */
        class ServiceBus
        {
        public:
            /**
             * @brief 获取单例实例
             */
            static ServiceBus &Instance()
            {
                static ServiceBus instance;
                return instance;
            }
            // ====================== 服务管理 ====================
            /**
             * @brief 注册服务实例
             * @param service 服务实例
             * @return 是否注册成功
             */
            bool RegisterService(std::shared_ptr<IService> service)
            {
                if (!service)
                {
                    LOG_ERROR << "service is null";
                    return false;
                }
                std::unique_lock lock(service_mutex_);
                std::string service_name = service->GetServiceName();
                if (services_.find(service_name) != services_.end())
                {
                    LOG_WARN << "service " << service_name << " already exists";
                    return false;
                }
                services_[service_name] = service;
                return true;
            }
            bool UnregisterService(std::shared_ptr<IService> service)
            {
                if (!service)
                {
                    LOG_ERROR << "service is null";
                    return false;
                }
                std::unique_lock lock(service_mutex_);
                std::string service_name = service->GetServiceName();
                if (services_.find(service_name) == services_.end())
                {
                    LOG_WARN << "service " << service_name << " not exists";
                    return false;
                }
                return services_.erase(service_name) > 0;
            }
            /**
             * @brief 获取服务实例
             * @param service_name 服务名称
             * @return 服务器实例指针，不存在返回nullptr
             */
            IServicePtr GetServiceInstance(const std::string &service_name)
            {
                std::shared_lock lock(service_mutex_);
                auto it = services_.find(service_name);
                if (it == services_.end())
                {
                    return nullptr;
                }
                return it->second;
            }
            /**
             * @brief 获取所有运行中的服务
             * @return 服务名称列表
             */
            std::vector<std::string> GetRunningServices() const
            {
                std::unique_lock lock(service_mutex_);
                std::vector<std::string> services;
                services.reserve(services_.size());
                for (const auto &pair : services_)
                {
                    services.push_back(pair.first);
                }
                return services;
            }
            // ===================== 事件发布订阅 ===================
            /**
             * @brief 事件订阅
             * @param event_name 事件名称
             * @param handler 事件处理器
             * @return 订阅ID(用于取消订阅)
             */
            int Subscribe(const std::string &event_name, const EventHandler &handler)
            {
                std::unique_lock lock(service_mutex_);
                int subscription_id = next_subscription_id_++;
                subscriptions_[event_name][subscription_id] = handler;
                return subscription_id;
            }
            /**
             * @brief 取消事件订阅
             * @param event_name 事件名称
             * @param subscription_id 订阅ID
             * @return 是否取消成功
             */
            bool Unsubscribe(const std::string &event_name, int subscription_id)
            {
                std::unique_lock lock(service_mutex_);
                auto it = subscriptions_.find(event_name);
                if (it == subscriptions_.end())
                {
                    LOG_WARN << "event " << event_name << " not exists";
                    return false;
                }
                return it->second.erase(subscription_id) > 0;
            }
            /**
             * @brief 发布事件
             * @param event_name 事件名称
             * @param data 事件数据(json格式)
             */
            void PublishEvent(const std::string &event_name, const nlohmann::json &data)
            {
                std::vector<EventHandler> handlers;
                {
                    std::unique_lock lock(service_mutex_);
                    auto it = subscriptions_.find(event_name);
                    if (it == subscriptions_.end())
                    {
                        LOG_WARN << "event " << event_name << " not exists";
                        return;
                    }
                    handlers.reserve(it->second.size());
                    for (const auto &pair : it->second)
                    {
                        handlers.push_back(pair.second);
                    }
                }
                // 调用所有处理器
                for (const auto &handler : handlers)
                {
                    try
                    {
                        handler(data);
                    }
                    catch (const std::exception &e)
                    {
                        // 记录错误但不影响其他订阅者
                        LOG_ERROR << "event handler error";
                    }
                }
            }
            // ===================== RPC调用 =====================
            /**
             * @brief 调用其他服务（同步RPC）
             * @param service_name 服务名称
             * @param request 请求对象
             * @return 响应对象
             */
            Response CallService(const std::string &service_name, const Request &request)
            {
                auto service = GetServiceInstance(service_name);
                if (!service)
                {
                    return Response::Error(ErrorCode::INTERNAL_ERROR, "service not found");
                }
                if (!service->HealthCheck())
                {
                    return Response::Error(ErrorCode::INTERNAL_ERROR, "service unavailable" + service_name);
                }
                return service->HandleRequest(request);
            }
            /**
             * @brief 调用其他服务（异步RPC）
             * @param service_name 服务名称
             * @param request 请求对象
             * @param callback 回调函数
             */
            void CallServiceAsync(const std::string &service_name, const Request &request,
                                  std::function<void(const Response &)> callback)
            {
                auto service = GetServiceInstance(service_name);
                if (!service)
                {
                    if (callback)
                    {
                        callback(Response::Error(ErrorCode::INTERNAL_ERROR, "service not found:" + service_name));
                    }
                    return;
                }
                if (!service->HealthCheck())
                {
                    if (callback)
                    {
                        callback(Response::Error(ErrorCode::INTERNAL_ERROR, "service unavailable:" + service_name));
                    }
                    return;
                }
                return service->HandleRequestAsync(request, callback);
            }
            // ===================== 统计信息 =====================
            /**
             * @brief 获取服务总线统计信息
             *
             */
            nlohmann::json GetStatistics() const
            {
                nlohmann::json stats;
                {
                    std::unique_lock lock(service_mutex_);
                    stats["running_services"] = services_.size();
                    nlohmann::json services_info = nlohmann::json::array();
                    for (const auto &pair : services_)
                    {
                        nlohmann::json service_info;
                        service_info["name"] = pair.first;
                        service_info["version"] = pair.second->GetServiceVersion();
                        service_info["description"] = pair.second->GetServicedescription();
                        service_info["health"] = pair.second->HealthCheck();
                        services_info.push_back(service_info);
                    }
                    stats["services"] = services_info;
                    stats["event_types"] = subscriptions_.size();
                    int toltal_subscriptions = 0;
                    for (auto &pair : subscriptions_)
                    {
                        toltal_subscriptions += pair.second.size();
                    }
                    stats["total_subscriptions"] = toltal_subscriptions;
                }
                return stats;
            }
            /**
             * @brief 清空所有数据(用于测试)
             *
             */
            void Clear()
            {
                std::unique_lock lock(service_mutex_);
                services_.clear();
                subscriptions_.clear();
            }

        private:
            ServiceBus() : next_subscription_id_(1)
            {
            }
            ~ServiceBus() = default;
            ServiceBus(const ServiceBus &) = delete;
            ServiceBus &operator=(const ServiceBus &) = delete;
            // 服务实例管理
            mutable std::shared_mutex service_mutex_;
            std::map<std::string, IServicePtr> services_;
            // 事件订阅管理
            std::map<std::string, std::map<int, EventHandler>> subscriptions_;
            int next_subscription_id_ = 1;
        };
    }
}